package RPC;

import Constant.constant;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeoutException;

public class RpcClient {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1.创建链接工厂
        ConnectionFactory factory=new ConnectionFactory();
        //2.设置参数
        factory.setHost(constant.localhost);
        factory.setPort(constant.port);
        factory.setVirtualHost(constant.VirtuHost);
        factory.setUsername(constant.UserName);
        factory.setPassword(constant.Password);
        //3.创立链接
        Connection connection=factory.newConnection();
        //4.创建channel信道
        Channel channel=connection.createChannel();
        channel.queueDeclare(constant.RPC_REQUEST_QUEUE,true,false,false,null);
        channel.queueDeclare(constant.RPC_RESPONSE_QUEUE,true,false,false,null);

        //发送请求
        String msg="hello rpc...";
        //设置请求的唯一标识
        String correlationID = UUID.randomUUID().toString();
        //设置请求的相关属性
        AMQP.BasicProperties props=new AMQP.BasicProperties().builder()
                .correlationId(correlationID)
                .replyTo(constant.RPC_RESPONSE_QUEUE)
                .build();
        //使用的是内置交换机，则直接使用队列名即可
        channel.basicPublish("",constant.RPC_REQUEST_QUEUE,props,msg.getBytes(StandardCharsets.UTF_8));

        //接收响应
        //使用阻塞队列，来存储响应信息
        //为什么要使用阻塞队列
        //因为这个是异步的，当RPC客户端发送请求后，就要立即返回结果，但是RPC服务器还没来得及处理返回结果
        final BlockingQueue<String> response=new ArrayBlockingQueue<>(1);
        DefaultConsumer consumer=new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
            String respMsg=new String(body);
                System.out.println("接收到回调信息:"+respMsg);
                if(correlationID.equals(properties.getCorrelationId())){
                    //放入阻塞队列
                    response.offer(respMsg);
                }
            }
        };
        //第二个参数是是否自动确认
        channel.basicConsume(constant.RPC_RESPONSE_QUEUE,true,consumer);
        //如果阻塞队列为空 就阻塞等待
        String result = response.take();
        System.out.println("[RPC Client 响应结果]:"+result);


    }
}
